package icursoft.educationms.ui.user;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import icursoft.educationms.BaseActivity;
import icursoft.educationms.EducationMSApplication;
import icursoft.educationms.R;
import icursoft.educationms.bean.MTalkResultBO;
import icursoft.educationms.bean.StudentInfoBO;
import icursoft.educationms.http.HttpCallBack;
import icursoft.educationms.http.HttpResult;
import icursoft.educationms.servive.PreferencesService;
import icursoft.educationms.util.CommUtil;
import icursoft.educationms.util.Const;
import icursoft.educationms.util.MachTalkUtil;
import icursoft.educationms.util.TimeCountDown;
import okhttp3.Call;
import okhttp3.Response;

import static icursoft.educationms.util.MachTalkUtil.BASE_URL;
import static icursoft.educationms.util.MachTalkUtil.OKGO_URL;


/**
 * Created by Administrator on 2016/10/18.
 */

public class RegisterActivity extends BaseActivity {

    private String mUser, mPassword, mConfirmPassword, mValidationCode;
    private EditText mUserView, mPasswordView, mConfirmPasswordView, mValidationCodeView;
    private TextView title_tv, right_tv, mCodeRequestBtn;
    //TimeCountDown timeCountDown;
    private int i;
    /**
     * 注册有效性验证
     */
    public boolean attemptRegister() {

        if (TextUtils.isEmpty(mUser)) {
            CommUtil.showToast(mContext, R.string.prompt_phone, Toast.LENGTH_SHORT);
            return false;
        }

        if (TextUtils.isEmpty(mValidationCode)) {
            CommUtil.showToast(mContext, R.string.prompt_validation_code, Toast.LENGTH_SHORT);
            return false;
        }

        if (TextUtils.isEmpty(mPassword)) {
            CommUtil.showToast(mContext, R.string.prompt_password, Toast.LENGTH_SHORT);
            return false;
        } else if (mPassword.length() < Const.MIN_PASSWORD_LENGTH||mPassword.length() >18) {
            CommUtil.showToast(mContext, R.string.error_short_limited_password, Toast.LENGTH_SHORT);
            return false;
        } else if (mPassword.matches("[0-9]+")
                || mPassword.matches("[a-zA-Z]+")
                || mPassword.matches("[^0-9a-zA-Z]+")) {
            CommUtil.showToast(mContext, R.string.error_password_limit, Toast.LENGTH_SHORT);
            return false;
        } else if (mPassword.contains(" ")) {
            CommUtil.showToast(mContext, R.string.error_password_whitespace, Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(mConfirmPassword)) {
            CommUtil.showToast(mContext, R.string.confirm_field_required, Toast.LENGTH_SHORT);
            return false;
        }
        if (!TextUtils.isEmpty(mPassword)
                && !TextUtils.isEmpty(mConfirmPassword)
                && !mPassword.equals(mConfirmPassword)) {
            CommUtil.showToast(mContext, R.string.error_inconsistent_password, Toast.LENGTH_SHORT);
            return false;
        }
        SMSSDK.submitVerificationCode("86", mUser, mValidationCode);
//        if (DataSupport.where("phone = ?" , mUserView.getText().toString()).find(StudentInfoBO.class).isEmpty()){
//            //将收到的验证码和手机号提交再次核对
//            SMSSDK.submitVerificationCode("86", mUser, mValidationCode);
//        }else {
//            Toast.makeText(getApplicationContext(), "该手机号已经注册",
//                    Toast.LENGTH_SHORT).show();
//            mUserView.setText("");
//        }
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void setupViews() {

        title_tv = getView(R.id.title_tv);
        title_tv.setText(R.string.title_activity_register);
        right_tv = getView(R.id.right_tv);
        right_tv.setText(R.string.text_next);

        mUserView = getView(R.id.register_edittext_telephone_num);
        mPasswordView = getView(R.id.register_edittext_password);
        mConfirmPasswordView = getView(R.id.register_edittext_password_ensure);
        mValidationCodeView = getView(R.id.register_edittext_validate_code);
        mCodeRequestBtn = getView(R.id.image_button_get_validation);

        mCodeRequestBtn.setOnClickListener(this);
        getView(R.id.right_layout).setOnClickListener(this);
        getView(R.id.left_layout).setOnClickListener(this);
    }

    @Override
    protected void initialized() {
        //timeCountDown = new TimeCountDown(mCodeRequestBtn, 60000, 1000, "重新获取", "重新获取");
        SMSSDK.initSDK(this, "1cb1009f4ed60", "781244c832b4b22967b4029afa80f220");
        //注册回调监听接口
        final EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object o) {
                Message message = new Message();
                message.arg1 = event;
                message.arg2 = result;
                message.obj = o;
                handler.sendMessage(message);
            }
        };
        SMSSDK.registerEventHandler(eventHandler);
    }

    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();

    }

    @Override
    public void onClick(View view) {
        mUser = mUserView.getText().toString();
        mPassword = mPasswordView.getText().toString();
        mConfirmPassword = mConfirmPasswordView.getText().toString();
        mValidationCode = mValidationCodeView.getText().toString();
        switch (view.getId()) {
            case R.id.left_layout:
                finish();
                break;
            case R.id.right_layout:

                if (attemptRegister()) {

                }
                break;
            case R.id.image_button_get_validation:
                if (TextUtils.isEmpty(mUserView.getText().toString())) {
                    CommUtil.showToast(mContext, R.string.prompt_phone, Toast.LENGTH_SHORT);
                    return;
                }
                //if (DataSupport.where("phone = ?" , mUser).find(StudentInfoBO.class).isEmpty()){
                    if (CommUtil.judgePhoneNums(this,mUser)) {
                        SMSSDK.getVerificationCode("86", mUser);
                        //timeCountDown.start();
                        mCodeRequestBtn.setClickable(false);
                        i = 60;
                        mCodeRequestBtn.setText("重新发送(" + i + ")");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (; i > 0; i--) {
                                    handler.sendEmptyMessage(1);
                                    if (i <= 0) {
                                        break;
                                    }
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                                handler.sendEmptyMessage(2);
                            }
                        }).start();
                        break;
                    }else {
                        mUserView.setText("");
                    }
//                }else {
//                    Toast.makeText(getApplicationContext(), "该手机号已经注册",
//                            Toast.LENGTH_SHORT).show();
//                    mUserView.setText("");
//                }
                break;
        }
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                mCodeRequestBtn.setText("重新发送" + i + "s");
            } else if (msg.what == 2) {
                mCodeRequestBtn.setText("获取验证码");
                mCodeRequestBtn.setClickable(true);
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        Log.e(TAG, "handleMessage: " + event + "," + result + "," + data);
                        //将登录信息保存至数据库
                        /*App.editor.putString(App.USERNAME_REGISTER , mPhoneEdt.getText().toString());
                        App.editor.putString(App.USERPWD_REGISTER , mPwdEdt.getText().toString());
                        App.editor.commit();*/
                        StudentInfoBO userLoginInfo = new StudentInfoBO();
                        userLoginInfo.setPhone(mUserView.getText().toString());
                        userLoginInfo.save();
                        MachTalkUtil.addUser(RegisterActivity.this,addUserCallback, mUserView.getText().toString(), mPasswordView.getText().toString());

                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        boolean smart = (Boolean) data;
                        if (smart){
                        }else {
                            //获取验证码成功
                            Toast.makeText(getApplicationContext(), "正在获取验证码",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                }else  if (result == SMSSDK.RESULT_ERROR){
                    Throwable throwable = (Throwable) data;
                    throwable.printStackTrace();
                    JSONObject object;
                    try {
                        object = new JSONObject(throwable.getMessage());
                        //Toast.makeText(mContext, "错误代码：" + object.optInt("status")+","+object.optString("detail"), Toast.LENGTH_SHORT).show();
                        mValidationCodeView.setError(object.optString("detail"));
                        Log.e(TAG, "错误代码：" + object.optInt("status")+","+object.optString("detail"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    StringCallback addUserCallback = new StringCallback() {
        @Override
        public void onSuccess(String str, okhttp3.Call call, Response response) {
            //上传成功
            Log.e("wangshu", str);
            HttpResult param = EducationMSApplication.GSON.fromJson(str , HttpResult.class);
            if (param.getMsg() >= 0) {
                MachTalkUtil.userLogin(mContext,loginCallback, mUser, mPassword);
            }
            CommUtil.showToast(mContext, param.getMsgbox().toString(),  Toast.LENGTH_SHORT);

        }
        @Override
        public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            //这里回调上传进度(该回调在主线程,可以直接更新ui)
        }
    };
    StringCallback loginCallback = new StringCallback() {
        @Override
        public void onSuccess(String str, okhttp3.Call call, okhttp3.Response response) {
            //上传成功
            Log.e("wangshu", str);
            HttpResult param = EducationMSApplication.GSON.fromJson(str , HttpResult.class);
            if (param.getMsg() >= 0) {
                PreferencesService.getInstance(mContext).setIsLogin(true);
                //PreferencesService.getInstance(mContext).setUserId();
                PreferencesService.getInstance(mContext).setUserPhone(mUserView.getText().toString());
                PreferencesService.getInstance(mContext).setTokenLong(param.getData().toString());
//                    PreferencesService.getInstance(mContext).setTokenShort(result.getTokenShort());
                startActivity(ImpPerInfActivity.class);
                finish();
//                    startActivity(new Intent(LoginActivity.this, InticareDActivity.class));
//                    overridePendingTransition(R.anim.fade, R.anim.hold);
//                    finish();
            } else {

            }
            CommUtil.showToast(mContext, param.getMsgbox().toString(),  Toast.LENGTH_SHORT);
        }
        @Override
        public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            //这里回调上传进度(该回调在主线程,可以直接更新ui)
        }
    };
}